#include "SpriteRenderer.h"

using namespace SolidityEngine;

SpriteRenderer::SpriteRenderer(Image* img, const Vector2D& pivot, RenderTarget target):
    Renderer(target),
    _image(NULL),
    _pivot(0.5,0.5),
    _subimagerect(Rect())
{
    //ctor
}

SpriteRenderer::~SpriteRenderer()
{
    //dtor
}

SpriteRenderer* SpriteRenderer::_Clone()
{
    return new SpriteRenderer(*this);
}

void SpriteRenderer::SetSubImage(const Rect& coords)
{
    _subimagerect=coords;
}

void SpriteRenderer::SetImage(Image* image)
{
    _image=image;
}

Image* SpriteRenderer::GetImage()
{
    return _image;
}

void SpriteRenderer::_Render(SDL_Surface* surface)
{
    if(_image){
        SDL_Surface* isurf=_image->GetSurface();

        float clipx=_image->Width()*_subimagerect.X();
        float clipy=_image->Height()*_subimagerect.Y();
        float clipw=_image->Width()*_subimagerect.Width();
        float cliph=_image->Height()*_subimagerect.Height();

        float p_offset_x=clipw*_pivot.X();
        float p_offset_y=cliph*_pivot.Y();

        SDL_Rect cliprect;

        cliprect.x=clipx;
        cliprect.y=clipy;
        cliprect.w=clipw;
        cliprect.h=cliph;

        SDL_SetClipRect(isurf,&cliprect);

        Transform2D* trans=_gameobject->GetComponent<Transform2D>();

        SDL_Rect t_rect;
        t_rect.x=trans->Position().X()-p_offset_x;
        t_rect.y=trans->Position().Y()-p_offset_y;
        t_rect.w=cliprect.w;
        t_rect.h=cliprect.h;

        SDL_BlitSurface(isurf,&isurf->clip_rect,surface,&t_rect);
    }
}

